D:\a\cssh-rs\cssh-rs\cssh-rs-core\src\cli.rs
Line | Count | Source |
1 | | //! CLI interface |
2 | | |
3 | | use crate::client::main as client_main; |
4 | | use crate::daemon::{main as daemon_main, resolve_cluster_tags}; |
5 | | use crate::utils::config::{ClientConfig, Cluster, Config, ConfigOpt, DaemonConfig}; |
6 | | use crate::utils::windows::WindowsApi; |
7 | | use crate::{ |
8 | | current_exe_path, get_console_window_handle, init_logger, is_launched_from_gui, |
9 | | spawn_console_process, WindowsSettingsDefaultTerminalApplicationGuard, |
10 | | }; |
11 | | use clap::{ArgAction, CommandFactory, Parser, Subcommand}; |
12 | | |
13 | | #[cfg(test)] |
14 | | use mockall::{automock, predicate::*}; |
15 | | use windows::Win32::UI::HiDpi::PROCESS_PER_MONITOR_DPI_AWARE; |
16 | | |
17 | | use cssh_rs_meta::PACKAGE_NAME; |
18 | | |
19 | | /// Cross-platform cluster SSH tool |
20 | | /// |
21 | | /// The main CLI arguments |
22 | | #[derive(Parser, Debug)] |
23 | | #[clap(author, version, about, long_about = None)] |
24 | | pub struct Args { |
25 | | /// Optional subcommand |
26 | | /// Usually not specified by the user |
27 | | #[clap(subcommand)] |
28 | | command: Option<Commands>, |
29 | | /// Optional username used to connect to the hosts |
30 | | #[clap(long, short = 'u')] |
31 | | username: Option<String>, |
32 | | /// Optional port used for all SSH connections |
33 | | #[clap(long, short = 'p')] |
34 | | port: Option<u16>, |
35 | | /// Hosts and/or cluster tag(s) to connect to |
36 | | /// |
37 | | /// Hosts or cluster tags might use brace expansion, |
38 | | /// but need to be properly quoted. |
39 | | /// |
40 | | /// E.g.: `cssh-rs.exe "host{1..3}" hostA` |
41 | | /// |
42 | | /// Hosts can include a username which will take precedence over the |
43 | | /// username given via the `-u` option and over any ssh config value. |
44 | | /// |
45 | | /// E.g.: `cssh-rs.exe -u user3 user1@host1 userA@hostA host3` |
46 | | /// |
47 | | /// Hosts can include a port number which will take precedence over the |
48 | | /// port given via the `-p` option. |
49 | | /// |
50 | | /// E.g.: `cssh-rs.exe -p 33 host1:11 host2:22 host3` |
51 | | /// |
52 | | /// If no hosts are provided and the application is launched in a new console window |
53 | | /// (e.g. by double clicking the executable in the File Explorer), |
54 | | /// it will launch in interactive mode. |
55 | | #[clap(required = false, global = true)] |
56 | | hosts: Vec<String>, |
57 | | /// Enable extensive logging |
58 | | #[clap(short, long, action=ArgAction::SetTrue)] |
59 | | debug: bool, |
60 | | } |
61 | | |
62 | | /// The ``command`` CLI subcommand |
63 | | #[derive(Debug, Subcommand, PartialEq)] |
64 | | enum Commands { |
65 | | /// Subcommand that will launch a single client window |
66 | | /// |
67 | | /// connecting to the given host with the given username. |
68 | | /// It will also try to read input from a daemon via the named pipe. |
69 | | Client { |
70 | | /// Host to connect to |
71 | | host: String, |
72 | | /// Named-pipe path of the daemon control channel |
73 | | #[clap(long)] |
74 | | daemon_channel: Option<String>, |
75 | | }, |
76 | | /// Subcommand that will launch the daemon window. |
77 | | /// |
78 | | /// The daemon is responsible to launch the client windows, |
79 | | /// one for each given host. |
80 | | /// For each client a named pipe will be created and any keystrokes |
81 | | /// the daemon window receives are forwarded via the pipes to all the clients. |
82 | | /// Also handles control mode. |
83 | | Daemon {}, |
84 | | /// Write a default config file at the given output path. |
85 | | /// |
86 | | /// Values that differ from the defaults can be set via the options. |
87 | | GenerateConfig { |
88 | | /// Path to an SSH config file. When set, the launched program |
89 | | /// receives `-F <PATH>` as the first two argv entries. |
90 | | #[clap(long)] |
91 | | ssh_config_path: Option<String>, |
92 | | /// Program launched to establish each SSH connection. |
93 | | /// Defaults to the `client.program` config default when unset. |
94 | | #[clap(long)] |
95 | | program: Option<String>, |
96 | | /// Program arguments written to `client.arguments`, replacing the |
97 | | /// default bare `<user>@<host>` placeholder; repeatable and must |
98 | | /// include it. Use the `--arguments=VALUE` form for values starting |
99 | | /// with `-`, e.g. `--arguments=-XY --arguments={{USERNAME_AT_HOST}}`. |
100 | | #[clap(long)] |
101 | | arguments: Vec<String>, |
102 | | /// Name of the single cluster written to the config. |
103 | | #[clap(long, default_value = "default")] |
104 | | cluster: String, |
105 | | /// Path of the config file to write. Defaults to |
106 | | /// `cssh-rs-config.toml` next to the running executable. |
107 | | #[clap(long)] |
108 | | output: Option<String>, |
109 | | /// Value written to `daemon.console_color`; unset keeps the config default. |
110 | | #[clap(long)] |
111 | | daemon_console_color: Option<u16>, |
112 | | }, |
113 | | } |
114 | | |
115 | | /// Main Entrypoint struct |
116 | | /// |
117 | | /// Used to implement the entrypoint functions of the different |
118 | | /// subcommands |
119 | | pub struct MainEntrypoint; |
120 | | |
121 | | /// Trait for Args operations to enable mocking in tests |
122 | | #[cfg_attr(test, automock)] |
123 | | pub trait ArgsCommand { |
124 | | /// Print help message |
125 | | fn print_help(&self) -> Result<(), std::io::Error>; |
126 | | } |
127 | | |
128 | | /// Default implementation of ArgsCommand trait |
129 | | pub struct CLIArgsCommand; |
130 | | |
131 | | impl ArgsCommand for CLIArgsCommand { |
132 | 0 | fn print_help(&self) -> Result<(), std::io::Error> { |
133 | 0 | return Args::command().print_help(); |
134 | 0 | } |
135 | | } |
136 | | |
137 | | /// Trait for logger initialization to enable mocking in tests |
138 | | #[cfg_attr(test, automock)] |
139 | | pub trait LoggerInitializer { |
140 | | /// Initialize logger with the given name |
141 | | fn init_logger(&self, name: &str); |
142 | | } |
143 | | |
144 | | /// Default implementation of LoggerInitializer trait |
145 | | pub struct CLILoggerInitializer; |
146 | | |
147 | | impl LoggerInitializer for CLILoggerInitializer { |
148 | 0 | fn init_logger(&self, name: &str) { |
149 | 0 | init_logger(name); |
150 | 0 | } |
151 | | } |
152 | | |
153 | | /// Trait for writing output to enable dependency injection and testing |
154 | | #[cfg_attr(test, automock)] |
155 | | pub trait Output { |
156 | | /// Write a line to the output |
157 | | fn println(&mut self, text: &str); |
158 | | /// Write text without a newline to the output |
159 | | fn print(&mut self, text: &str); |
160 | | /// Write a line to stderr |
161 | | fn eprintln(&mut self, text: &str); |
162 | | /// Flush the output |
163 | | fn flush(&mut self); |
164 | | } |
165 | | |
166 | | /// Default implementation of Output trait that writes to stdout/stderr |
167 | | pub struct CLIOutput; |
168 | | |
169 | | impl Output for CLIOutput { |
170 | 0 | fn println(&mut self, text: &str) { |
171 | 0 | println!("{text}"); |
172 | 0 | } |
173 | | |
174 | 0 | fn print(&mut self, text: &str) { |
175 | 0 | print!("{text}"); |
176 | 0 | } |
177 | | |
178 | 0 | fn eprintln(&mut self, text: &str) { |
179 | 0 | eprintln!("{text}"); |
180 | 0 | } |
181 | | |
182 | 0 | fn flush(&mut self) { |
183 | | use std::io::Write; |
184 | 0 | std::io::stdout().flush().unwrap(); |
185 | 0 | } |
186 | | } |
187 | | |
188 | | /// Trait for reading input to enable dependency injection and testing |
189 | | #[cfg_attr(test, automock)] |
190 | | pub trait Input { |
191 | | /// Read a line from stdin |
192 | | fn read_line(&mut self) -> Result<String, std::io::Error>; |
193 | | } |
194 | | |
195 | | /// Default implementation of Input trait that reads from stdin |
196 | | pub struct CLIInput; |
197 | | |
198 | | impl Input for CLIInput { |
199 | 0 | fn read_line(&mut self) -> Result<String, std::io::Error> { |
200 | 0 | let mut input = String::new(); |
201 | 0 | std::io::stdin().read_line(&mut input)?; |
202 | 0 | return Ok(input); |
203 | 0 | } |
204 | | } |
205 | | |
206 | | /// Trait for environment operations to enable dependency injection and testing |
207 | | #[cfg_attr(test, automock)] |
208 | | pub trait Environment { |
209 | | /// Get current executable path |
210 | | fn current_exe(&self) -> Result<std::path::PathBuf, std::io::Error>; |
211 | | /// Set current directory |
212 | | fn set_current_dir(&self, path: &std::path::Path) -> Result<(), std::io::Error>; |
213 | | } |
214 | | |
215 | | /// Default implementation of Environment trait |
216 | | pub struct CLIEnvironment; |
217 | | |
218 | | impl Environment for CLIEnvironment { |
219 | 0 | fn current_exe(&self) -> Result<std::path::PathBuf, std::io::Error> { |
220 | 0 | return std::env::current_exe(); |
221 | 0 | } |
222 | | |
223 | 0 | fn set_current_dir(&self, path: &std::path::Path) -> Result<(), std::io::Error> { |
224 | 0 | return std::env::set_current_dir(path); |
225 | 0 | } |
226 | | } |
227 | | |
228 | | /// Trait for configuration management to enable dependency injection and testing |
229 | | #[cfg_attr(test, automock)] |
230 | | pub trait ConfigManager { |
231 | | /// Load configuration from the specified path |
232 | | fn load_config(&self, path: &str) -> Result<ConfigOpt, confy::ConfyError>; |
233 | | /// Store configuration to the specified path |
234 | | fn store_config(&self, path: &str, config: &Config) -> Result<(), confy::ConfyError>; |
235 | | } |
236 | | |
237 | | /// Default implementation of ConfigManager trait |
238 | | pub struct CLIConfigManager; |
239 | | |
240 | | impl ConfigManager for CLIConfigManager { |
241 | 0 | fn load_config(&self, path: &str) -> Result<ConfigOpt, confy::ConfyError> { |
242 | 0 | return confy::load_path(path); |
243 | 0 | } |
244 | | |
245 | 0 | fn store_config(&self, path: &str, config: &Config) -> Result<(), confy::ConfyError> { |
246 | 0 | return confy::store_path(path, config); |
247 | 0 | } |
248 | | } |
249 | | |
250 | | /// Trait defining the entrypoint functions of the different |
251 | | /// subcommands |
252 | | #[cfg_attr(test, automock)] |
253 | | pub trait Entrypoint { |
254 | | /// Entrypoint for the client subcommand |
255 | | fn client_main<W: WindowsApi + Clone + 'static>( |
256 | | &mut self, |
257 | | windows_api: &W, |
258 | | host: String, |
259 | | username: Option<String>, |
260 | | port: Option<u16>, |
261 | | daemon_channel: Option<String>, |
262 | | config: &ClientConfig, |
263 | | ) -> impl std::future::Future<Output = ()> + Send; |
264 | | /// Entrypoint for the daemon subcommand |
265 | | fn daemon_main<W: WindowsApi + Clone + 'static>( |
266 | | &mut self, |
267 | | windows_api: &W, |
268 | | hosts: Vec<String>, |
269 | | username: Option<String>, |
270 | | port: Option<u16>, |
271 | | config: &DaemonConfig, |
272 | | clusters: &[Cluster], |
273 | | debug: bool, |
274 | | ) -> impl std::future::Future<Output = ()> + Send; |
275 | | /// Entrypoint for the main command |
276 | | fn main<W: WindowsApi + 'static, C: ConfigManager + 'static>( |
277 | | &mut self, |
278 | | windows_api: &W, |
279 | | config_manager: &C, |
280 | | config_path: &str, |
281 | | config: &Config, |
282 | | args: Args, |
283 | | ); |
284 | | } |
285 | | |
286 | | impl Entrypoint for MainEntrypoint { |
287 | 0 | async fn client_main<W: WindowsApi + Clone + 'static>( |
288 | 0 | &mut self, |
289 | 0 | windows_api: &W, |
290 | 0 | host: String, |
291 | 0 | username: Option<String>, |
292 | 0 | port: Option<u16>, |
293 | 0 | daemon_channel: Option<String>, |
294 | 0 | config: &ClientConfig, |
295 | 0 | ) { |
296 | 0 | client_main(windows_api, host, username, port, daemon_channel, config).await; |
297 | 0 | } |
298 | | |
299 | 0 | async fn daemon_main<W: WindowsApi + Clone + 'static>( |
300 | 0 | &mut self, |
301 | 0 | windows_api: &W, |
302 | 0 | hosts: Vec<String>, |
303 | 0 | username: Option<String>, |
304 | 0 | port: Option<u16>, |
305 | 0 | config: &DaemonConfig, |
306 | 0 | clusters: &[Cluster], |
307 | 0 | debug: bool, |
308 | 0 | ) { |
309 | 0 | daemon_main(windows_api, hosts, username, port, config, clusters, debug).await; |
310 | 0 | } |
311 | | |
312 | 7 | fn main<W: WindowsApi + 'static, C: ConfigManager + 'static>( |
313 | 7 | &mut self, |
314 | 7 | windows_api: &W, |
315 | 7 | config_manager: &C, |
316 | 7 | config_path: &str, |
317 | 7 | config: &Config, |
318 | 7 | args: Args, |
319 | 7 | ) { |
320 | 7 | config_manager.store_config(config_path, config).unwrap(); |
321 | | |
322 | 7 | let mut daemon_args: Vec<String> = Vec::new(); |
323 | 7 | if args.debug { |
324 | 2 | daemon_args.push("-d".to_string()); |
325 | 5 | } |
326 | 7 | if let Some(username3 ) = args.username { |
327 | 3 | daemon_args.push("-u".to_string()); |
328 | 3 | daemon_args.push(username); |
329 | 4 | } |
330 | 7 | if let Some(port3 ) = args.port { |
331 | 3 | daemon_args.push("-p".to_string()); |
332 | 3 | daemon_args.push(port.to_string()); |
333 | 4 | } |
334 | 7 | daemon_args.push("daemon".to_string()); |
335 | | // Order is important here. If the hosts are passed before the daemon subcommand |
336 | | // it will not be recognizes as such and just be passed along as one of the hosts. |
337 | 7 | daemon_args.extend( |
338 | 7 | resolve_cluster_tags( |
339 | 9 | args.hosts.iter()7 .map7 (|host| return &**host).collect7 (), |
340 | 7 | &config.clusters, |
341 | | ) |
342 | 7 | .into_iter() |
343 | 9 | .map7 (|host| return host.to_string()), |
344 | | ); |
345 | 7 | let _guard = WindowsSettingsDefaultTerminalApplicationGuard::new(); |
346 | | // We must wait for the window to actually launch before dropping the _guard as we might otherwise |
347 | | // reset the configuration before the window was launched |
348 | 7 | let _ = get_console_window_handle( |
349 | 7 | windows_api, |
350 | 7 | spawn_console_process(windows_api, ¤t_exe_path(), daemon_args, true) |
351 | 7 | .expect("Failed to create process") |
352 | 7 | .dwProcessId, |
353 | 7 | ); |
354 | 7 | } |
355 | | } |
356 | | |
357 | | /// Display the interactive mode prompt and instructions |
358 | 12 | fn show_interactive_prompt<O: Output>(output: &mut O) { |
359 | 12 | output.println("\n=== Interactive Mode ==="); |
360 | 12 | output.println(&format!( |
361 | 12 | "Enter your {PACKAGE_NAME} arguments (or press Enter to exit):" |
362 | 12 | )); |
363 | 12 | output.println("Example: -u myuser host1 host2 host3"); |
364 | 12 | output.println("Example: --help"); |
365 | 12 | output.print("> "); |
366 | 12 | output.flush(); |
367 | 12 | } |
368 | | |
369 | | /// Read user input from stdin |
370 | | /// |
371 | | /// # Arguments |
372 | | /// |
373 | | /// * `input` - The Input trait object for reading from stdin |
374 | | /// |
375 | | /// # Returns |
376 | | /// |
377 | | /// * `Ok(Some(input))` - User provided input |
378 | | /// * `Ok(None)` - User wants to exit (empty input or "exit") |
379 | | /// * `Err(error)` - Error reading input |
380 | 16 | fn read_user_input<I: Input>(input: &mut I) -> Result<Option<String>, std::io::Error> { |
381 | 16 | let input_line14 = input.read_line()?2 ; |
382 | | |
383 | 14 | let input_trimmed = input_line.trim(); |
384 | 14 | if input_trimmed.is_empty() || input_trimmed.to_lowercase() == "exit"7 { |
385 | 9 | return Ok(None); |
386 | 5 | } |
387 | | |
388 | 5 | return Ok(Some(input_trimmed.to_string())); |
389 | 16 | } |
390 | | |
391 | | /// Handle special commands that don't need full parsing |
392 | | /// |
393 | | /// # Arguments |
394 | | /// |
395 | | /// * `input` - The user input string |
396 | | /// * `args_command` - The ArgsCommand trait object for printing help |
397 | | /// |
398 | | /// # Returns |
399 | | /// |
400 | | /// * `true` - Command was handled, continue loop |
401 | | /// * `false` - Command needs full parsing |
402 | 13 | fn handle_special_commands<A: ArgsCommand>(input: &str, args_command: &A) -> bool { |
403 | 13 | if input == "--help" || input == "-h"11 { |
404 | 3 | let _ = args_command.print_help(); |
405 | 3 | return true; |
406 | 10 | } |
407 | 10 | return false; |
408 | 13 | } |
409 | | |
410 | | /// Execute the interactively entered command, rejecting any subcommand. |
411 | | /// |
412 | | /// Interactive mode accepts only cssh options and positional arguments. |
413 | 6 | async fn execute_parsed_command< |
414 | 6 | W: WindowsApi + Clone + 'static, |
415 | 6 | T: Entrypoint, |
416 | 6 | A: ArgsCommand, |
417 | 6 | O: Output, |
418 | 6 | C: ConfigManager + 'static, |
419 | 6 | >( |
420 | 6 | windows_api: &W, |
421 | 6 | parsed_args: Args, |
422 | 6 | entrypoint: &mut T, |
423 | 6 | args_command: &A, |
424 | 6 | output: &mut O, |
425 | 6 | config_manager: &C, |
426 | 6 | config: &Config, |
427 | 6 | config_path: &str, |
428 | 6 | ) { |
429 | 6 | match &parsed_args.command { |
430 | 3 | Some(_) => { |
431 | 3 | output.eprintln( |
432 | 3 | "Subcommands are not supported in interactive mode. Use cssh options and positional arguments only.", |
433 | 3 | ); |
434 | 3 | } |
435 | | None => { |
436 | 3 | if !parsed_args.hosts.is_empty() { |
437 | 2 | entrypoint.main( |
438 | 2 | windows_api, |
439 | 2 | config_manager, |
440 | 2 | config_path, |
441 | 2 | config, |
442 | 2 | parsed_args, |
443 | 2 | ); |
444 | 2 | } else { |
445 | 1 | // Show help for empty hosts |
446 | 1 | let _ = args_command.print_help(); |
447 | 1 | } |
448 | | } |
449 | | } |
450 | 6 | } |
451 | | |
452 | | /// Run the interactive mode loop for GUI launches |
453 | 6 | async fn run_interactive_mode< |
454 | 6 | W: WindowsApi + Clone + 'static, |
455 | 6 | A: ArgsCommand, |
456 | 6 | T: Entrypoint, |
457 | 6 | O: Output, |
458 | 6 | I: Input, |
459 | 6 | C: ConfigManager + 'static, |
460 | 6 | >( |
461 | 6 | windows_api: &W, |
462 | 6 | args_command: &A, |
463 | 6 | mut entrypoint: T, |
464 | 6 | config_manager: &C, |
465 | 6 | config: &Config, |
466 | 6 | config_path: &str, |
467 | 6 | output: &mut O, |
468 | 6 | input: &mut I, |
469 | 6 | ) { |
470 | | loop { |
471 | 11 | show_interactive_prompt(output); |
472 | | |
473 | 11 | match read_user_input(input) { |
474 | 4 | Ok(Some(input_str)) => { |
475 | | // Handle special commands first |
476 | 4 | if handle_special_commands(&input_str, args_command) { |
477 | 1 | continue; |
478 | 3 | } |
479 | | |
480 | | // Parse the input as command line arguments |
481 | 3 | let input_args: Vec<&str> = input_str.split_whitespace().collect(); |
482 | 3 | let mut full_args = vec![PACKAGE_NAME]; |
483 | 3 | full_args.extend(input_args); |
484 | | |
485 | 3 | match Args::try_parse_from(full_args) { |
486 | 2 | Ok(parsed_args) => { |
487 | 2 | execute_parsed_command( |
488 | 2 | windows_api, |
489 | 2 | parsed_args, |
490 | 2 | &mut entrypoint, |
491 | 2 | args_command, |
492 | 2 | output, |
493 | 2 | config_manager, |
494 | 2 | config, |
495 | 2 | config_path, |
496 | 2 | ) |
497 | 2 | .await; |
498 | | } |
499 | 1 | Err(err) => { |
500 | 1 | output.eprintln(&format!("\nError parsing arguments: {err}")); |
501 | 1 | } |
502 | | } |
503 | | } |
504 | | Ok(None) => { |
505 | 6 | return; |
506 | | } |
507 | 1 | Err(err) => { |
508 | 1 | output.eprintln(&format!("Error reading input: {err}")); |
509 | 1 | } |
510 | | } |
511 | | } |
512 | 6 | } |
513 | | |
514 | | /// Build the config emitted by `generate-config`. A set `ssh_config_path` both |
515 | | /// prepends `-F <path>` to `client.arguments` and sets `client.ssh_config_path`; |
516 | | /// non-empty `arguments` replace the default `<user>@<host>` placeholder. |
517 | 8 | fn build_generate_config( |
518 | 8 | hosts: Vec<String>, |
519 | 8 | cluster: &str, |
520 | 8 | program: Option<&str>, |
521 | 8 | ssh_config_path: Option<&str>, |
522 | 8 | arguments: Vec<String>, |
523 | 8 | daemon_console_color: Option<u16>, |
524 | 8 | ) -> Config { |
525 | 8 | let mut config = Config { |
526 | 8 | clusters: vec![Cluster { |
527 | 8 | name: cluster.to_string(), |
528 | 8 | hosts, |
529 | 8 | }], |
530 | 8 | ..Config::default() |
531 | 8 | }; |
532 | | |
533 | 8 | if let Some(program5 ) = program { |
534 | 5 | config.client.program = program.to_string(); |
535 | 5 | }3 |
536 | | |
537 | 8 | if let Some(console_color2 ) = daemon_console_color { |
538 | 2 | config.daemon.console_color = console_color; |
539 | 6 | } |
540 | | |
541 | 8 | let mut client_arguments = Vec::new(); |
542 | 8 | if let Some(path3 ) = ssh_config_path { |
543 | 3 | client_arguments.push("-F".to_string()); |
544 | 3 | client_arguments.push(path.to_string()); |
545 | 3 | config.client.ssh_config_path = path.to_string(); |
546 | 5 | } |
547 | 8 | if arguments.is_empty() { |
548 | 7 | client_arguments.push(config.client.username_host_placeholder.clone()); |
549 | 7 | } else { |
550 | 1 | client_arguments.extend(arguments); |
551 | 1 | } |
552 | 8 | config.client.arguments = client_arguments; |
553 | | |
554 | 8 | return config; |
555 | 8 | } |
556 | | |
557 | | /// Write the generated config to `output_path` (or `default_config_path`) and |
558 | | /// print its absolute path to `output`; error if `hosts` is empty or the write |
559 | | /// fails. |
560 | 4 | fn run_generate_config<O: Output, C: ConfigManager>( |
561 | 4 | output: &mut O, |
562 | 4 | config_manager: &C, |
563 | 4 | default_config_path: &str, |
564 | 4 | hosts: Vec<String>, |
565 | 4 | cluster: &str, |
566 | 4 | program: Option<&str>, |
567 | 4 | ssh_config_path: Option<&str>, |
568 | 4 | arguments: Vec<String>, |
569 | 4 | output_path: Option<&str>, |
570 | 4 | daemon_console_color: Option<u16>, |
571 | 4 | ) -> Result<(), String> { |
572 | 4 | if hosts.is_empty() { |
573 | 1 | return Err("generate-config requires at least one host".to_string()); |
574 | 3 | } |
575 | | |
576 | 3 | let config = build_generate_config( |
577 | 3 | hosts, |
578 | 3 | cluster, |
579 | 3 | program, |
580 | 3 | ssh_config_path, |
581 | 3 | arguments, |
582 | 3 | daemon_console_color, |
583 | | ); |
584 | 3 | let target_path = std::path::PathBuf::from(output_path.unwrap_or(default_config_path)); |
585 | 3 | let target_str = target_path.to_string_lossy().into_owned(); |
586 | | |
587 | 3 | config_manager |
588 | 3 | .store_config(&target_str, &config) |
589 | 3 | .map_err(|err| return format!0 ("Failed to write config to {target_str}: {err}"))?0 ; |
590 | | |
591 | | // canonicalize can fail on some filesystems; fall back to a lexical absolute path. |
592 | 3 | let resolved = std::fs::canonicalize(&target_path) |
593 | 3 | .or_else(|_| return std::path::absolute(&target_path)) |
594 | 3 | .map(|p| return p.to_string_lossy().into_owned()) |
595 | 3 | .unwrap_or(target_str); |
596 | 3 | output.println(&resolved); |
597 | 3 | return Ok(()); |
598 | 4 | } |
599 | | |
600 | | /// The main entrypoint |
601 | | /// |
602 | | /// Parses the CLI arguments, |
603 | | /// loads an existing config or writes the default config to disk, and |
604 | | /// calls the respective subcommand. |
605 | | /// If no subcommand is given we launch the daemon subcommand in a new window. |
606 | 11 | pub async fn main< |
607 | 11 | W: WindowsApi + Clone + 'static, |
608 | 11 | E: Entrypoint, |
609 | 11 | O: Output, |
610 | 11 | I: Input, |
611 | 11 | Env: Environment, |
612 | 11 | A: ArgsCommand, |
613 | 11 | L: LoggerInitializer, |
614 | 11 | C: ConfigManager + 'static, |
615 | 11 | >( |
616 | 11 | windows_api: &W, |
617 | 11 | args: Args, |
618 | 11 | mut entrypoint: E, |
619 | 11 | output: &mut O, |
620 | 11 | input: &mut I, |
621 | 11 | environment: &Env, |
622 | 11 | args_command: &A, |
623 | 11 | logger_initializer: &L, |
624 | 11 | config_manager: &C, |
625 | 11 | ) { |
626 | | // CRITICAL: Check GUI launch BEFORE any output to console |
627 | 11 | let launched_from_gui = is_launched_from_gui(windows_api); |
628 | | |
629 | | // Set DPI awareness programatically. Using the manifest is the recommended way |
630 | | // but conhost.exe does not do any manifest loading. |
631 | | // https://github.com/microsoft/terminal/issues/18464#issuecomment-2623392013 |
632 | 11 | if let Err(err5 ) = windows_api.set_process_dpi_awareness(PROCESS_PER_MONITOR_DPI_AWARE) { |
633 | 5 | output.eprintln(&format!( |
634 | 5 | "Failed to set DPI awareness programatically: {err:?}" |
635 | 5 | )); |
636 | 6 | } |
637 | 11 | match environment.current_exe() { |
638 | 10 | Ok(path) => match path.parent() { |
639 | 1 | None => { |
640 | 1 | output.eprintln("Failed to get executable path parent working directory"); |
641 | 1 | } |
642 | 9 | Some(exe_dir) => { |
643 | 9 | environment |
644 | 9 | .set_current_dir(exe_dir) |
645 | 9 | .expect("Failed to change current working directory"); |
646 | 9 | } |
647 | | }, |
648 | 1 | Err(_) => { |
649 | 1 | output.eprintln("Failed to get executable directory"); |
650 | 1 | } |
651 | | } |
652 | | |
653 | 11 | let config_path = format!("{PACKAGE_NAME}-config.toml"); |
654 | | |
655 | | // Dispatch before load_config so a broken on-disk config cannot break generation. |
656 | | if let Some(Commands::GenerateConfig { |
657 | 1 | ssh_config_path, |
658 | 1 | program, |
659 | 1 | arguments, |
660 | 1 | cluster, |
661 | 1 | output: output_path, |
662 | 1 | daemon_console_color, |
663 | 5 | }) = &args.command |
664 | | { |
665 | 1 | if let Err(err0 ) = run_generate_config( |
666 | 1 | output, |
667 | 1 | config_manager, |
668 | 1 | &config_path, |
669 | 1 | args.hosts.to_owned(), |
670 | 1 | cluster, |
671 | 1 | program.as_deref(), |
672 | 1 | ssh_config_path.as_deref(), |
673 | 1 | arguments.to_owned(), |
674 | 1 | output_path.as_deref(), |
675 | 1 | *daemon_console_color, |
676 | 1 | ) { |
677 | 0 | output.eprintln(&err); |
678 | 0 | std::process::exit(1); |
679 | 1 | } |
680 | 1 | return; |
681 | 10 | } |
682 | | |
683 | 10 | let config_on_disk: ConfigOpt = config_manager.load_config(&config_path).unwrap(); |
684 | 10 | let config: Config = config_on_disk.into(); |
685 | | |
686 | 4 | match &args.command { |
687 | 0 | Some(Commands::GenerateConfig { .. }) => unreachable!("handled before config load"), |
688 | | Some(Commands::Client { |
689 | 2 | host, |
690 | 2 | daemon_channel, |
691 | | }) => { |
692 | 2 | if args.debug { |
693 | 1 | logger_initializer.init_logger(&format!("cssh-rs_client_{host}")); |
694 | 1 | } |
695 | 2 | entrypoint |
696 | 2 | .client_main( |
697 | 2 | windows_api, |
698 | 2 | host.to_owned(), |
699 | 2 | args.username.to_owned(), |
700 | 2 | args.port, |
701 | 2 | daemon_channel.to_owned(), |
702 | 2 | &config.client, |
703 | 2 | ) |
704 | 2 | .await; |
705 | | } |
706 | | Some(Commands::Daemon {}) => { |
707 | 2 | if args.debug { |
708 | 1 | logger_initializer.init_logger("cssh-rs_daemon"); |
709 | 1 | } |
710 | 2 | entrypoint |
711 | 2 | .daemon_main( |
712 | 2 | windows_api, |
713 | 2 | args.hosts.to_owned(), |
714 | 2 | args.username.clone(), |
715 | 2 | args.port, |
716 | 2 | &config.daemon, |
717 | 2 | &config.clusters, |
718 | 2 | args.debug, |
719 | 2 | ) |
720 | 2 | .await; |
721 | | } |
722 | | None => { |
723 | | // If no hosts provided, show help and handle GUI vs console launch |
724 | 6 | if args.hosts.is_empty() { |
725 | 5 | let _ = args_command.print_help(); |
726 | | |
727 | | // If launched from GUI, allow user to input arguments interactively |
728 | 5 | if launched_from_gui { |
729 | 2 | run_interactive_mode( |
730 | 2 | windows_api, |
731 | 2 | args_command, |
732 | 2 | entrypoint, |
733 | 2 | config_manager, |
734 | 2 | &config, |
735 | 2 | &config_path, |
736 | 2 | output, |
737 | 2 | input, |
738 | 2 | ) |
739 | 2 | .await; |
740 | 3 | } |
741 | 5 | return; |
742 | 1 | } |
743 | | |
744 | 1 | entrypoint.main(windows_api, config_manager, &config_path, &config, args); |
745 | | } |
746 | | } |
747 | 11 | } |
748 | | |
749 | | #[cfg(test)] |
750 | | #[path = "./tests/test_cli.rs"] |
751 | | mod test_cli; |